<template>
  <div class="select-component">
    <!-- 现有筛选项 -->
    <a-row class="mb10" v-if="showDataList.length" gutter="16">
      <a-col :span="8" v-for="(item, index) in showDataList" :key="index">
        <div
          class="mb10"
          style="display: flex"
          v-if="(showFormItem && index > 2) || index <= 2"
        >
          <label class="w110 dib"
            >{{ item.columnName }}：
            <a-tooltip
              v-if="item.columnName === '全流程剩余时效'"
              style="display: inline"
            >
              <template #title>
                <div>筛选结果为小于对应的时间的CP数；</div>
              </template>
              <InfoCircleOutlined /> </a-tooltip
          ></label>
          <a-select
            v-if="item.model === 0 && item.columnName == '预警'"
            style="display: inline-block; width: 100%"
            v-model:value="formdata[item.searchStr]"
            placeholder="请选择"
          >
            <a-select-option :value="1">
              待企划评级
              <a-tooltip>
                <template #title>
                  <div>预计上架日期前20天未填写企划评级</div>
                </template>
                <InfoCircleOutlined />
              </a-tooltip>
            </a-select-option>
            <a-select-option :value="2"
              >SA款待下单
              <a-tooltip>
                <template #title>
                  <div>
                    预计上架日期前12天，企划评级为S/A，且独立站有效采购次数小于2
                  </div>
                </template>
                <InfoCircleOutlined />
              </a-tooltip>
            </a-select-option>
            <a-select-option :value="3">已回货15天未上架 </a-select-option>
            <a-select-option :value="4">临期预警 </a-select-option>
            <a-select-option :value="5">超期预警 </a-select-option>
          </a-select>
          <a-select
            v-if="item.model === 0 && item.columnName !== '预警'"
            style="display: inline-block; width: 100%"
            :placeholder="'搜索' + item.columnName"
            :maxTagCount="2"
            mode="tags"
            v-model:value="formdata[item.searchStr]"
            :filter-option="filterOption"
            option-label-prop="label"
            show-search
            allow-clear
            @focus="
              () => {
                onFocus(item)
              }
            "
          >
            <a-select-option
              v-for="val in item.options"
              :value="val.value"
              :label="val.label"
              :key="val.value"
              >{{ val.label }}</a-select-option
            >
          </a-select>
          <remote-select
            v-if="item.model === 2"
            :placeholder="'搜索' + item.columnName"
            style="display: inline-block; width: 100%"
            :maxTagCount="1"
            v-model:value="formdata[item.searchStr]"
            :menuName="item.menuName"
            mode="tags"
            :token-separators="[' ', ',']"
            :columnName="item.searchStr"
          />
          <a-cascader
            v-if="item.model === 4"
            style="display: inline-block; width: 100%"
            v-model:value="formdata[item.searchStr]"
            :options="
              item.searchStr === 'themeIdList'
                ? store.themeListAll
                : productCategoryDict
            "
            change-on-select
            :placeholder="'搜索' + item.columnName"
          />
          <a-range-picker
            dropdownClassName="date-range"
            v-if="item.model === 1"
            style="display: inline-block; width: 100%"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model:value="formdata[item.searchStr]"
            :placeholder="['开始日期', '结束日期']"
          />
          <a-radio-group
            style="display: inline-block; width: 100%"
            v-if="item.model === 5"
            v-model:value="formdata[item.searchStr]"
          >
            <a-radio
              v-for="(val, inde) in item.options"
              :key="inde"
              :value="val.value"
              >{{ val.label }}</a-radio
            >
          </a-radio-group>
          <a-textarea
            style="display: inline-block; width: 100%"
            v-if="item.model === 3"
            v-model:value="formdata[item.searchStr]"
            :placeholder="'搜索' + item.columnName"
            :row="3"
          ></a-textarea>
          <a-input
            style="display: inline-block; width: 100%"
            v-if="item.model === 8"
            v-model:value="formdata[item.searchStr]"
            :placeholder="'搜索' + item.columnName"
          ></a-input>
          <a-input-number
            v-if="item.model === 9"
            style="display: inline-block; width: 100%"
            v-model:value="formdata[item.searchStr]"
            :placeholder="'搜索' + item.columnName"
            :min="0"
          >
            <a-tooltip v-if="item.model === 9" style="display: inline">
              <template #title>
                <div>筛选结果为小于对应的时间的CP数；</div>
              </template>
              <InfoCircleOutlined />
            </a-tooltip>
          </a-input-number>
        </div>
      </a-col>
      <a-col v-if="searchData.length" :span="24" style="text-align: right">
        <a
          class="mr20 fs12"
          @click="showMoreSelect = true"
          v-if="searchData.length > 3"
        >
          更多筛选
          <DownOutlined />
        </a>
        <a class="mr20 fs12" @click="toggle" v-if="showDataList.length > 3">
          {{ showFormItem ? '收起' : '展开' }}
          <UpOutlined v-if="showFormItem" />
          <DownOutlined v-else />
        </a>
        <a-button size="small" class="mr20" @click="reset(1)">重置</a-button>
        <a-button size="small" type="primary" class="mr20" @click="pageInit(1)"
          >查询</a-button
        >
        <a-dropdown :trigger="['hover']">
          <a-button :loading="store.isloading" size="small">导出</a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item key="0" @click="exportExcel(1)"
                >上架文档</a-menu-item
              >
              <a-menu-item key="1" @click="exportExcel(2)"
                >列表数据</a-menu-item
              >
              <a-menu-item key="2" @click="exportExcel(3)"
                >SizeGuide</a-menu-item
              >
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
    </a-row>

    <!-- 更多筛选 -->
    <a-drawer
      title="更多筛选"
      placement="right"
      class="myDrawer"
      v-model:visible="showMoreSelect"
      width="50%"
    >
      <a-row class="pb50">
        <a-col :span="24" v-for="(item, index) in searchData" :key="index">
          <div v-if="!item.isSelected">
            <label class="db mt10 mb5">{{ item.columnName }}：</label>
            <a-select
              v-if="item.model === 0 && item.columnName == '预警'"
              class="w90p"
              v-model:value="hiddenFormdata[item.searchStr]"
              placeholder="请选择"
            >
              <a-select-option :value="1">
                待企划评级
                <a-tooltip>
                  <template #title>
                    <div>预计上架日期前20天未填写企划评级</div>
                  </template>
                  <InfoCircleOutlined />
                </a-tooltip>
              </a-select-option>
              <a-select-option :value="2"
                >SA款待下单
                <a-tooltip>
                  <template #title>
                    <div>
                      预计上架日期前12天，企划评级为S/A，且独立站有效采购次数小于2
                    </div>
                  </template>
                  <InfoCircleOutlined />
                </a-tooltip>
              </a-select-option>
              <a-select-option :value="3">已回货15天未上架 </a-select-option>
              <a-select-option :value="4">临期预警 </a-select-option>
              <a-select-option :value="5">超期预警 </a-select-option>
            </a-select>
            <a-select
              v-if="item.model === 0 && item.columnName !== '预警'"
              class="w90p"
              :placeholder="'搜索' + item.columnName"
              :maxTagCount="2"
              mode="tags"
              v-model:value="hiddenFormdata[item.searchStr]"
              :filter-option="filterOption"
              option-label-prop="label"
              show-search
              allow-clear
              @focus="
                () => {
                  onFocus(item)
                }
              "
            >
              <a-select-option
                v-for="val in item.options"
                :value="val.value"
                :label="val.label"
                :key="val.value"
                >{{ val.label }}</a-select-option
              >
            </a-select>
            <remote-select
              v-if="item.model === 2"
              :placeholder="'搜索' + item.columnName"
              style="width: 90%"
              :maxTagCount="2"
              v-model:value="hiddenFormdata[item.searchStr]"
              :menuName="item.menuName"
              mode="tags"
              :token-separators="[' ', ',']"
              :columnName="item.searchStr"
            />
            <a-cascader
              v-if="item.model === 4"
              class="w90p"
              v-model:value="hiddenFormdata[item.searchStr]"
              :options="
                item.searchStr === 'themeIdList'
                  ? store.themeListAll
                  : productCategoryDict
              "
              change-on-select
              :placeholder="'搜索' + item.columnName"
            />
            <a-range-picker
              v-if="item.model === 1"
              dropdownClassName="date-range"
              class="w90p"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              v-model:value="hiddenFormdata[item.searchStr]"
              :placeholder="['开始日期', '结束日期']"
            />
            <a-radio-group
              class="w90p"
              v-if="item.model === 5"
              v-model:value="hiddenFormdata[item.searchStr]"
            >
              <a-radio
                v-for="(val, inde) in item.options"
                :key="inde"
                :value="val.value"
                >{{ val.label }}</a-radio
              >
            </a-radio-group>
            <a-textarea
              class="w90p"
              v-if="item.model === 3"
              v-model:value="hiddenFormdata[item.searchStr]"
              :placeholder="'搜索' + item.columnName"
              :row="3"
            ></a-textarea>
            <a-input
              class="w90p"
              v-if="item.model === 8"
              v-model:value="hiddenFormdata[item.searchStr]"
              :placeholder="'搜索' + item.columnName"
              :row="3"
            ></a-input>
          </div>
        </a-col>
        <div class="tac w100p" v-if="!hiddenItemList.length">
          <a-empty description="暂无数据" />
        </div>
      </a-row>
      <div class="fixedBottom" style="position: absolute">
        <a-button class="fl" size="small" @click="showSelectSet = true"
          >筛选设置</a-button
        >
        <div class="fr">
          <a-button size="small" type="link" @click="reset(2)">重置</a-button>
          <a-button size="small" type="primary" @click="pageInit(2)"
            >筛选</a-button
          >
        </div>
      </div>
    </a-drawer>
    <!-- 筛选设置 -->
    <a-drawer
      title="筛选设置"
      placement="right"
      class="myDrawer"
      v-model:visible="showSelectSet"
      width="30%"
      destroyOnClose
    >
      <div class="pb50">
        <div style="color: #1890ff">展示的筛选项</div>
        <draggable
          v-model="showItemList"
          item-key="index"
          tag="ul"
          draggable=".columnItem"
          @end="onDragEnd"
        >
          <template #item="{ element, index }">
            <li
              class="columnItem"
              style="
                background: #f0f0f0;
                padding: 8px;
                overflow: hidden;
                margin-top: 10px;
              "
            >
              <div class="fl">
                <UnorderedListOutlined />
                {{ element.columnName }}
              </div>
              <MinusSquareOutlined
                class="fr fs16 cp"
                @click="changeStatus(1, index)"
              />
            </li>
          </template>
        </draggable>

        <div class="mt20" style="color: #1890ff">隐藏的筛选项</div>
        <draggable
          v-model="hiddenItemList"
          item-key="index"
          tag="ul"
          draggable=".columnItem"
          @end="onDragEnd"
        >
          <template #item="{ element, index }">
            <li
              class="columnItem"
              style="
                background: #f0f0f0;
                padding: 8px;
                overflow: hidden;
                margin-top: 10px;
              "
            >
              <div class="fl">
                <UnorderedListOutlined />
                {{ element.columnName }}
              </div>
              <PlusSquareOutlined
                class="fr fs16 cp"
                @click="changeStatus(2, index)"
              />
            </li>
          </template>
        </draggable>
      </div>
      <div class="fixedBottom" style="position: absolute">
        <div class="fr">
          <a-button class="mr10" size="small" @click="showSelectSet = false"
            >取消</a-button
          >
          <a-button type="primary" size="small" @click="saveChange"
            >保存</a-button
          >
        </div>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { reactive, toRefs, onMounted, inject } from 'vue'
import useAPI from 'UseApi'
import draggable from 'vuedraggable'
// import { debounce } from 'lodash-es'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import {
  DownOutlined,
  UpOutlined,
  UnorderedListOutlined,
  MinusSquareOutlined,
  PlusSquareOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'
import {
  config_list_menu_field_post,
  config_update_menu_field_post,
  config_list_column_post
} from 'server/modules/1890'
// import { config_list_config_theme_post } from '@/server/modules/4802.js'
const APIS = useAPI(null, [1890])
export default {
  props: {
    menuName: {
      type: String,
      default: ''
    },
    showMore: {
      type: Boolean,
      default: true
    }
  },
  components: {
    DownOutlined,
    UpOutlined,
    UnorderedListOutlined,
    MinusSquareOutlined,
    PlusSquareOutlined,
    draggable,
    InfoCircleOutlined
  },
  setup(props, { emit }) {
    const store = inject('pageState')
    console.log(store)
    const state = reactive({
      store,
      productCategoryDict: [],
      showMoreSelect: false,
      showFormItem: false,
      showSelectSet: false,
      formdata: {},
      hiddenFormdata: {},
      showItemList: [],
      hiddenItemList: [],
      searchData: [],
      showDataList: [],
      initformdata: {},
      showSelectBox: true
    })
    onMounted(() => {
      const { productCategoryDict } = APIS.config_list_product_category_post_()
      state.productCategoryDict = productCategoryDict
      methods.getMenuListField()
      // methods.getThemeList()
    })
    // watch(
    //   () => state.showMoreSelect,
    //   val => {
    //     if (!val) {
    //       state.hiddenFormdata = {}
    //     }
    //   },
    //   {
    //     immediate: true
    //   }
    // )
    const methods = {
      // async getThemeList() {
      //   const { success, retInfo, data } = await config_list_config_theme_post(
      //     {}
      //   )
      //   if (success) {
      //     console.log(data)
      //     state.themeList = data
      //     methods.changeData(state.themeList)
      //   } else {
      //     message.error(retInfo)
      //   }
      // },
      // changeData(data) {
      //   data.forEach(item => {
      //     item.children = item.childList
      //     item.value = item.id
      //     item.label = item.theme
      //     if (item.childList && item.childList.length) {
      //       methods.changeData(item.childList)
      //     }
      //   })
      // },
      exportExcel(val) {
        const searchdata = {
          ...state.formdata,
          ...state.hiddenFormdata
        }
        emit('exportExcel', val, cloneDeep(searchdata))
      },
      async getConfigColumn(item) {
        const { success, retInfo, data } = await config_list_column_post({
          menuName: item.menuName,
          columnName: item.searchStr
        })
        if (success) {
          item.options = (data || [])
            .filter(_ => {
              return _.key != null && _.key !== ''
            })
            .map(_ => {
              return {
                label: _.value,
                value: _.key
              }
            })
        } else {
          console.log(data)
          message.error(retInfo)
        }
      },
      async saveChange() {
        const { success, data, retInfo } = await config_update_menu_field_post({
          beforeFieldPos: [...state.hiddenItemList, ...state.showItemList],
          menuName: state.searchData[0].menuName
        })
        if (success) {
          console.log(data)
          message.success(retInfo)
          state.showMoreSelect = false
          state.showSelectSet = false
          methods.getMenuListField()
        } else {
          message.error(retInfo)
        }
      },
      async getMenuListField() {
        state.showDataList = []
        state.formdata = {}
        state.hiddenFormdata = {}
        const { success, data, retInfo } = await config_list_menu_field_post({
          menuName: props.menuName
        })
        if (success) {
          state.searchData = data
          state.searchData.forEach(item => {
            if (item.isSelected) {
              state.formdata[item.searchStr] = undefined
            } else {
              state.hiddenFormdata[item.searchStr] = undefined
            }
            if (item.model === 5) {
              item.options = item.fieldDescVo
              const checkedValue = item.options.filter(item => item.checked)
              if (checkedValue.length) {
                if (item.isSelected) {
                  state.formdata[item.searchStr] = checkedValue[0].value
                } else {
                  state.hiddenFormdata[item.searchStr] = checkedValue[0].value
                }
              }
            }
          })
          state.initformdata = cloneDeep(state.formdata)
          state.hiddeninitformdata = cloneDeep(state.hiddenFormdata)
          if (!state.searchData || !state.searchData.length) return
          state.showDataList = cloneDeep(
            state.searchData.filter(item => item.isSelected)
          )
          state.showItemList = cloneDeep(
            state.searchData.filter(item => item.isSelected)
          )
          state.hiddenItemList = cloneDeep(
            state.searchData.filter(item => !item.isSelected)
          )
        } else {
          message.error(retInfo)
        }
      },
      filterOption(input, option) {
        console.log(input, option)
        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      changeInput(e, key, index) {
        const val = e.target.value
        emit('changeInput', val, key, index, props.tableName)
      },
      toggle() {
        state.showFormItem = !state.showFormItem
        emit('resize')
      },
      reset() {
        state.formdata = cloneDeep(state.initformdata)
        state.hiddenFormdata = cloneDeep(state.hiddeninitformdata)
        // const keys = Object.keys(state.formdata)
        // const showformData = cloneDeep(state.formdata)
        // state.hiddenItemList.forEach(item => {
        //   if (keys.includes(item.searchStr)) {
        //     delete showformData[item.searchStr]
        //   }
        // })
        const searchdata = {
          ...state.formdata,
          ...state.hiddenFormdata
        }
        emit('reset', cloneDeep(searchdata))
      },
      pageInit() {
        // const keys = Object.keys(state.formdata)
        // const showformData = cloneDeep(state.formdata)
        // state.hiddenItemList.forEach(item => {
        //   if (keys.includes(item.searchStr)) {
        //     delete showformData[item.searchStr]
        //   }
        // })

        setTimeout(() => {
          const searchdata = {
            ...state.formdata,
            ...state.hiddenFormdata
          }
          console.log(searchdata, 'console.log(searchdata)')
          emit('search', cloneDeep(searchdata))
        }, 200)
      },
      onDragEnd(evt) {
        evt.preventDefault()
        console.log('拖动前的索引 :' + evt.oldIndex)
        console.log('拖动后的索引 :' + evt.newIndex)
        // const oldValue = state.searchData[evt.oldIndex]
        // state.searchData.splice(evt.oldIndex, 1)
        // state.searchData.splice(evt.newIndex, 0, oldValue)
      },
      // 列筛选
      onFocus(item) {
        methods.getConfigColumn(item, state)
        // item.options = cloneDeep(configOptions)
      },
      changeStatus(val, index) {
        let arr = []
        if (val === 1) {
          arr = state.showItemList.splice(index, 1)
          state.hiddenItemList = [...state.hiddenItemList, ...arr]
        } else {
          arr = state.hiddenItemList.splice(index, 1)
          state.showItemList = [...state.showItemList, ...arr]
        }
        state.hiddenItemList.forEach(item => (item.isSelected = 0))
        state.showItemList.forEach(item => (item.isSelected = 1))
      }
    }
    return {
      ...toRefs(state),
      ...methods
      // ...toRefs(store)
    }
  }
}
</script>
<style lang="scss" scoped>
label {
  font-size: 12px;
}
:deep(.ant-drawer-body) {
  padding-top: 0 !important;
}
:deep(.ant-radio-wrapper) {
  margin-right: 4px;
}
</style>
<style lang="scss">
.date-range {
  .ant-calendar-prev-year-btn,
  .ant-calendar-next-year-btn {
    display: none !important;
  }
}
</style>
